<template>
  <div class="course-details-manage p-4" tabindex="0">
    <!-- 操作按钮区域 -->
    <div class="mb-4 flex flex-wrap gap-2 items-center">
      <el-input
        v-model="queryParams.courseName"
        placeholder="请输入课程名称"
        style="width: 200px"
        clearable
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select
        v-model="queryParams.roundId"
        placeholder="请选择轮次"
        clearable
        style="width: 200px"
        @change="handleSearch"
      >
        <el-option
          v-for="item in roundOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column prop="roundName" label="轮次" min-width="120">
      </el-table-column>
      <el-table-column prop="courseName" label="课程" min-width="120">
      </el-table-column>
      <el-table-column prop="username" label="授课教师" min-width="100">
      </el-table-column>
      <el-table-column
        prop="chooseNum"
        label="当前选课人数"
        width="130"
        align="center"
      />
      <el-table-column
        prop="personMax"
        label="最大选课人数"
        width="130"
        align="center"
      />
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="scope">
          <div class="flex space-x-2">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              type="success"
              size="small"
              plain
              @click="handleAdd(scope.row)"
            >
              加入
            </el-button>
          </div>
          
        </template>
        
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="queryParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="prev, pager, next"
          :total="total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 选课详情对话框 -->
    <el-dialog title="选课详情" v-model="detailDialogVisible" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="选课ID">{{
          courseDetail.id
        }}</el-descriptions-item>
        <el-descriptions-item label="轮次">{{
          courseDetail.roundName
        }}</el-descriptions-item>
        <el-descriptions-item label="课程">{{
          courseDetail.courseName
        }}</el-descriptions-item>
        <el-descriptions-item label="授课教师">{{
          courseDetail.username
        }}</el-descriptions-item>
        <el-descriptions-item label="当前选课人数">{{
          courseDetail.chooseNum
        }}</el-descriptions-item>
        <el-descriptions-item label="最大选课人数">{{
          courseDetail.personMax
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          formatDateTime(courseDetail.createTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{
          formatDateTime(courseDetail.updateTime)
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
// 选课详情
import { getcourseDetails } from '@/api/courseDetails'
// 轮次
import { getroundlist } from '@/api/round'
// 课程
import { getcourse } from '@/api/courses'
// 用户
import { userlist } from '@/api/usersManage'
// 学生选课操作
import { addcourseselection } from '@/api/courseSelection'
import { useUserStore } from "@/stores/user.js"

const userStore = useUserStore()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  courseName: '',
  roundId: undefined,
})

// 轮次
const roundOptions = ref([])
// 课程
const courseOptions = ref([])
// 用户
const userOptions = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const jumpPage = ref(1)
const selectedRows = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const courseDetail = reactive({
  id: '',
  roundId: '',
  courseId: '',
  userId: '',
  personMax: 0,
  createTime: '',
  updateTime: '',
})

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  return dateTimeString.replace('T', ' ').replace(/\.000Z$/, '')
}


// 获取轮次列表
const getRoundList = async () => {
  try {
    const { code, data, msg } = await getroundlist({
      pageNum: 1,
      pageSize: 100,
    })
    if (code !== 200) {
      throw new Error(msg)
    }
    roundOptions.value = data.records.map((item) => ({
      value: item.id,
      label: item.name,
    }))
  } catch (error) {
    ElMessage.error(error.message || '获取轮次数据失败')
  }
}

// 获取课程列表
const getCourseList = async () => {
  try {
    const { code, data, msg } = await getcourse({
      pageNum: 1,
      pageSize: 100,
    })
    if (code !== 200) {
      throw new Error(msg)
    }
    courseOptions.value = data.records.map((item) => ({
      value: item.id,
      label: item.courseName,
    }))
  } catch (error) {
    ElMessage.error(error.message || '获取课程数据失败')
  }
}

// 获取用户列表
const getUserList = async () => {
  try {
    const { code, data, msg } = await userlist({
      pageNum: 1,
      pageSize: 100,
    })
    if (code !== 200) {
      throw new Error(msg)
    }
    userOptions.value = data.records.map((item) => ({
      value: item.id,
      label: item.name,
    }))
  } catch (error) {
    ElMessage.error(error.message || '获取用户数据失败')
  }
}

// 获取选课详情列表
const getCourseDetailsList = async () => {
  loading.value = true
  try {
    const { code, data, msg } = await getcourseDetails(queryParams)
    if (code !== 200) {
      throw new Error(msg)
    }
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    ElMessage.error(error.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

// 处理加入
const handleAdd = async (row) => {
  try {
    const { code, msg } = await addcourseselection({
    roundId: row.roundId,
    tcdId: row.id,
    userId: userStore.userInfo.id,
   })
   if (code !== 200) {
    throw new Error(msg)
   }
   ElMessage.success('加入成功')
   // 刷新列表
   getCourseDetailsList()
  } catch (error) {
    ElMessage.error(error.message || '加入失败')
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getCourseDetailsList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getCourseDetailsList()
}

// 添加页面跳转功能
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value)
  if (
    isNaN(pageNum) ||
    pageNum < 1 ||
    pageNum > Math.ceil(total.value / queryParams.pageSize)
  ) {
    ElMessage.warning('请输入有效的页码')
    jumpPage.value = queryParams.pageNum
    return
  }
  queryParams.pageNum = pageNum
  getCourseDetailsList()
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getCourseDetailsList()
}

// 处理详情
const handleDetail = (row) => {
  // 填充详情数据
  Object.assign(courseDetail, row)
  detailDialogVisible.value = true
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 监听courseName变化，实现防抖搜索
let searchTimer = null
watch(
  () => queryParams.courseName,
  (newVal) => {
    if (searchTimer) clearTimeout(searchTimer)
    searchTimer = setTimeout(() => {
      handleSearch()
    }, 500) // 500毫秒防抖
  }
)

onMounted(() => {
  // 获取选项数据
  getRoundList()
  getCourseList()
  getUserList()
  // 获取列表数据
  getCourseDetailsList()
})
</script>

<style lang="less" scoped>
.course-details-manage {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .el-table {
    height: calc(100vh - 270px);
  }
}
</style>
